import sys

import pymysql

# ============== 配置参数（根据实际情况修改） ==============
DB_CONFIG = {
    'host': '10.125.189.51',
    'port': 3306,
    'user': 'manager',
    'password': '123qwe!@#',
    'charset': 'utf8',
}
# 户口簿 project_info
# 基础信息库 basic_info_test
db_names = 'basic_info_test'


# ============== 辅助函数 ==============
def check_table_exists(conn, db_name, table_name):
    """检查表是否存在"""
    with conn.cursor() as cursor:
        cursor.execute(f"""
            SELECT COUNT(*)
            FROM information_schema.tables
            WHERE table_schema = %s AND table_name = %s
        """, (db_name, table_name))
        result = cursor.fetchone()
        if result:
            return result[0] > 0
        return False


def get_all_tables(conn, db_name):
    with conn.cursor() as cursor:
        cursor.execute(f"""
            SELECT *
            FROM information_schema.tables
            WHERE table_schema = %s
        """, db_name)
        result = cursor.fetchall()
        return [row[2] for row in result]  # 返回表名列表


# ============== 主逻辑 ==============
def main():
    conn = pymysql.connect(**DB_CONFIG)
    table_names = get_all_tables(conn, db_names)
    filter_table_names = ['sys_sequence']
    # 连接数据库
    for table_name in table_names:
        if table_name in filter_table_names:
            print(f"""
                INSERT INTO {table_name}
                SELECT *
                FROM  {db_names}.{table_name};
            """)
            print('\n')
            continue

        conn = pymysql.connect(**DB_CONFIG)
        try:
            # 检查目标表是否存在
            target_exists = check_table_exists(conn, db_names, table_name)
            # 如果存在则删除
            if target_exists:
                # drop table if exists {table_name};
                print(f"""
CREATE TABLE {table_name} LIKE {db_names}.{table_name}; -- 复制表结构
INSERT INTO {table_name}
SELECT *
FROM  {db_names}.{table_name};""")
                print('\n')
            else:
                print(f"""当前表:{table_name}在库中不存在""")
        except pymysql.MySQLError as e:
            print(f"数据库错误: {e}")
            sys.exit(1)
        finally:
            if 'conn' in locals() and conn.open:
                conn.close()


if __name__ == "__main__":
    main()
